from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.shortcuts import render
from rest_framework import request
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import OAuthQQUsers


#点击QQ登陆，跳转QQ登陆页面
class QQLoginView(APIView):
        #1.获取参数
    def get(self,request):
        state = request.query_params.get("state","/")
        #2.创建QQ对象
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state=state)
        #3.获取QQ授权链接
        login_url = oauth_qq.get_qq_url()
        #4.返回链接
        return Response({"auth_url":login_url})

#毁掉页面请求得到code,获取openid
class QQUserView(APIView):
    def get(self,request):
        # 获取参数
        code = request.query_params.get("code")
        #校验参数
        if not code:
            return Response("code丢失")

        #创建QQ对象
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state="/")

        #获取access_token
        access_token = oauth_qq.get_access_token(code)
        #获取openid
        openid = oauth_qq.get_open_id(access_token)
        # openid = "QWERT"
        # 通过code查询OAuthQQUsers表，判断时否为初次登陆，如果初次登陆则需要绑定“多美账号”
        try:
            oauth_qq_obj = OAuthQQUsers.objects.get(openid=openid)
        except OAuthQQUsers.DoesNotExist:
            '''初次登陆'''
            return Response("AAAA")

        else:
            #非初次登陆,通过外键获取用户对象
            user = oauth_qq_obj.user

            #获取token
            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            #返回数据
            return Response({
                "token": token,
                "username": user.username,
                "user_id": user.id
            })